package com.webmeeting.jsfbeans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.myframework.utils.constants.SiteConstants;
import com.myframework.utils.logutil.WMLogger;
import com.myframework.utils.stringutil.StringUtil;
import com.webmeeting.chat.wordchat.dao.daomanagers.UserManager;
import com.webmeeting.chat.wordchat.dao.entities.User;

@ManagedBean(name = "loginBean_home")
@RequestScoped
public class LoginBean {

	// username to login
	private String	username;
	// password to login
	private String	password;
	// header message
	private String	headerMsg;

	public String login() {
		if (StringUtil.isEmpty(this.username) || StringUtil.isEmpty(this.password)) {
			this.headerMsg = "Username and password can not be empty!";
			return "";
		}

		User user = UserManager.findUserByName(this.username);
		if (null == user) {
			WMLogger.debug("No user existing in this system with username: " + username);
			this.headerMsg = "No user existing in this system with username: " + username;
			return "";
		}
		if (!this.password.equals(user.getPassword())) {
			WMLogger.debug("Password is not correct.");
			this.headerMsg = "Password is not correct";
			return "";
		}

		FacesContext currContext = FacesContext.getCurrentInstance();
		((HttpSession) currContext.getExternalContext().getSession(true)).setAttribute("user", user);
		WMLogger.debug("User: " + this.username + " login to system.");
		return currContext.getExternalContext().getRequestContextPath() + "/index.xhtml";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getHeaderMsg() {
		return headerMsg;
	}

	public void setHeaderMsg(String headerMsg) {
		this.headerMsg = headerMsg;
	}

}
